package com.itsv.cyzx.adapter;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.itsv.cyzx.bean.ChatMsgEntity;
import com.itsv.xhyy.R;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 消息ListView的Adapter
 * 
 * @author way
 */
public class ChatMsgViewAdapter extends BaseAdapter {

	public static interface IMsgViewType {
		int IMVT_COM_MSG = 0;// 收到对方的消�?
		int IMVT_TO_MSG = 1;// 自己发�?出去的消�?
	}

	private static final int ITEMCOUNT = 2;// 消息类型的�?�?
	private List<ChatMsgEntity> coll;// 消息对象数组
	private LayoutInflater mInflater;
	private Context context;
	private static boolean playState = false; // 播放状态
	private MediaPlayer mediaPlayer;
	// 语音动画控制器
	Timer mTimer = null;
	// 语音动画控制任务
	TimerTask mTimerTask = null;
	// 记录语音动画图片
	int index = 1;
	AudioAnimationHandler audioAnimationHandler = null;

	public ChatMsgViewAdapter(Context context, List<ChatMsgEntity> coll) {
		this.coll = coll;
		this.context = context;
		mInflater = LayoutInflater.from(context);
	}

	public List<ChatMsgEntity> getColl() {
		return coll;
	}

	public void setColl(List<ChatMsgEntity> coll) {
		this.coll = coll;
	}

	public int getCount() {
		return coll.size();
	}

	public Object getItem(int position) {
		return coll.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	/**
	 * 得到Item的类型，是对方发过来的消息，还是自己发�?出去�?
	 */
	public int getItemViewType(int position) {
		ChatMsgEntity entity = coll.get(position);

		if (entity.getIsComMeg().equals("0")) {// 收到的消�?
			return IMsgViewType.IMVT_COM_MSG;
		} else {// 自己发�?的消�?
			return IMsgViewType.IMVT_TO_MSG;
		}
	}

	/**
	 * Item类型的�?�?
	 */
	public int getViewTypeCount() {
		return ITEMCOUNT;
	}

	ViewHolder viewHolder = null;

	public View getView(final int position, View convertView, ViewGroup parent) {

		final ChatMsgEntity entity = coll.get(position);
		final String isComMsg = entity.getIsComMeg();

		// ViewHolder viewHolder = null;
		if (convertView == null) {
			if (isComMsg.equals("0")) {
				convertView = mInflater.inflate(
						R.layout.chatting_item_msg_text_left, null);
			} else {
				convertView = mInflater.inflate(
						R.layout.chatting_item_msg_text_right, null);
			}

			viewHolder = new ViewHolder();
			viewHolder.tvSendTime = (TextView) convertView
					.findViewById(R.id.tv_sendtime);
			viewHolder.tvUserName = (TextView) convertView
					.findViewById(R.id.tv_username);
			viewHolder.tvContent = (TextView) convertView
					.findViewById(R.id.tv_chatcontent);
			viewHolder.voiceLy = (RelativeLayout) convertView
					.findViewById(R.id.voice_ly);
			viewHolder.voiceIv = (ImageView) convertView
					.findViewById(R.id.voice_iv);
			viewHolder.voiceL = (TextView) convertView
					.findViewById(R.id.voice_lth);
			viewHolder.isComMsg = isComMsg;

			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.tvSendTime.setText(entity.getDate());
		viewHolder.tvUserName.setText(entity.getName());
		if (entity.getMessage() != null && !entity.getMessage().equals("")) {

			viewHolder.tvContent.setText(entity.getMessage());
			viewHolder.tvContent.setVisibility(View.VISIBLE);
			System.out.println("msssssssssssss");
			viewHolder.voiceLy.setVisibility(View.GONE);
		} else {
			viewHolder.voiceIv.setTag(coll.get(position).getVoiceName());
			viewHolder.tvContent.setVisibility(View.GONE);
			viewHolder.voiceLy.setVisibility(View.VISIBLE);
			viewHolder.voiceL.setText(entity.getVoiceLength() + "”");
			System.out.println("vvvvvvvvvvvvvv");
			final ImageView imageView = (ImageView) convertView
					.findViewWithTag(coll.get(position).getVoiceName());
			viewHolder.voiceLy.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						if (isComMsg.equals("0")) {
							playVoice(entity.getVoiceName(), imageView, true);
						} else {
							playVoice(entity.getVoiceName(), imageView, false);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
		return convertView;
	}

	private void playVoice(String path, final ImageView imageView,
			final boolean isLeft) throws Exception {
		if (path != null && !path.equals("")) {
			if (!playState) {
				mediaPlayer = new MediaPlayer();
				System.out.println("-----------" + path);
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
					System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
					playAudioAnimation(imageView, isLeft, false);
				}
				mediaPlayer.setDataSource(path);
				mediaPlayer.prepare();
//				mediaPlayer.start();
				playState = true;
				playAudioAnimation(imageView, isLeft, playState);
				// 设置播放结束时监听
				mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						if (playState) {
							playState = false;
							playAudioAnimation(imageView, isLeft, playState);
							mediaPlayer.stop();
							mp.release();
						}
					}
				});
				if (mediaPlayer != null) {
					mediaPlayer.stop();
				}
				mediaPlayer.prepare();
				mediaPlayer.start();
			} else {
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
					playState = false;
					playAudioAnimation(imageView, isLeft, playState);
				} else {
					playState = false;
					playAudioAnimation(imageView, isLeft, playState);
				}
			}
		}

	}

	static class ViewHolder {
		public TextView tvSendTime;
		public TextView tvUserName;
		public TextView tvContent;
		public ImageView icon;
		public String isComMsg = "0";
		public RelativeLayout voiceLy;
		public ImageView voiceIv;
		public TextView voiceL;
	}

	/*
	 * 播放语音图标动画
	 */
	private void playAudioAnimation(final ImageView imageView, boolean isleft,
			final boolean isPlay) {
		// 定时器检查播放状态
		stopTimer();
		mTimer = new Timer();
		// 将要关闭的语音图片归位
		if (audioAnimationHandler != null) {
			Message msg = new Message();
			msg.what = 3;
			audioAnimationHandler.sendMessage(msg);
		}

		audioAnimationHandler = new AudioAnimationHandler(imageView, isleft);
		mTimerTask = new TimerTask() {
			public boolean hasPlayed = false;

			@Override
			public void run() {
				if (isPlay) {
					hasPlayed = true;
					index = (index + 1) % 3;
					Message msg = new Message();
					msg.what = index;
					audioAnimationHandler.sendMessage(msg);
				} else {
					// 当播放完时
					Message msg = new Message();
					msg.what = 3;
					audioAnimationHandler.sendMessage(msg);
					// 播放完毕时需要关闭Timer等
					if (hasPlayed) {
						stopTimer();
					}
				}
			}
		};
		// 调用频率为500毫秒一次
		mTimer.schedule(mTimerTask, 0, 500);
	}

	class AudioAnimationHandler extends Handler {
		ImageView imageView;
		// 判断是左对话框还是右对话框
		boolean isleft;

		public AudioAnimationHandler(ImageView imageView, boolean isleft) {
			this.imageView = imageView;
			// 判断是左对话框还是右对话框 我这里是在前面设置ScaleType来表示的
			this.isleft = isleft;
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 根据msg.what来替换图片，达到动画效果
			switch (msg.what) {
			case 0:
				System.out.println("+++++++++++" + isleft);
				imageView
						.setBackgroundResource(isleft ? R.drawable.chatfrom_voice_playing_f1
								: R.drawable.chatto_voice_playing_f1);
				break;
			case 1:
				imageView
						.setBackgroundResource(isleft ? R.drawable.chatfrom_voice_playing_f2
								: R.drawable.chatto_voice_playing_f2);
				break;
			case 2:
				imageView
						.setBackgroundResource(isleft ? R.drawable.chatfrom_voice_playing_f3
								: R.drawable.chatto_voice_playing_f3);
				break;
			default:
				imageView
						.setBackgroundResource(isleft ? R.drawable.chatfrom_voice_playing
								: R.drawable.chatto_voice_playing);
				break;
			}
		}

	}

	/**
	 * 停止
	 */
	private void stopTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}

		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}

	}
}
